package com.deewin.study.lock;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用 synchronize来同步
 *
 */
public class MyLock {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        TetsClass tc = new TetsClass();

        ExecutorService executorService =Executors.newCachedThreadPool();
        MyCall myCall = new MyCall(tc);

        MyCall[] mycalls = new MyCall[10];
        for(int i=0;i<10;i++){
            mycalls[i] = new MyCall(tc);
        }

        //1,中
//        Future<String> future = executorService.submit(myCall);
//        System.out.println(future.get());
//
//
//        executorService.shutdown();
//
        //2,
       // FutureTask futureTask = new FutureTask(myCall);
//        Thread thread = new Thread(futureTask);
//        thread.start();

        //3
//        Future f = executorService.submit(futureTask);
//        tc.sum();



        ///
        for(int i=0;i<10;i++){
            FutureTask futureTask = new FutureTask(mycalls[i]);
            executorService.submit(futureTask);
          //  System.out.println(futureTask.get());
        }
        tc.sum();

    }

}

/**
 *
 * while (alive){
 *             for(int i=0;i<ts.length;i++){
 *                 if(ts[i].isAlive()){
 *                     continue;
 *                 }
 *             }
 *             alive = false;
 *         }
 */

class MyCall implements Callable<String>{

    TetsClass tc;
    MyCall(){}

    MyCall(TetsClass tc){
        this.tc = tc;
    }


    @Override
    public String call() throws Exception {
        try {
            tc.dosometing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "done";
    }
}


class TetsClass{

    Lock lock = new ReentrantLock();
    int[] from = {12,454,54,12,5};

    int[] to = {434,454,12,54,34};

    public void  dosometing() throws InterruptedException {
        lock.lock();
        System.out.println("进来的线程是："+ Thread.currentThread().getName());
        for(int i=0;i<from.length;i++) {
            from[i] -=  5;
            TimeUnit.SECONDS.sleep(1);
            to[i] +=  5;
        }
        lock.unlock();
    }

    public  void sum(){
        System.out.println("原来的总数：");
        int f = 12+454+54+12+5;
        int t = 434+454+12+54+34;
        System.out.println("form:"+f);
        System.out.println("to:"+t);
        System.out.println("total="+(f+t));
        int formsum=0;
        for (int i=0;i<from.length;i++){
            formsum += from[i];
        }
        int tosum=0;
        for (int i=0;i<to.length;i++){
            tosum += to[i];
        }
        System.out.println("后来的sum：");
        System.out.println("form  "+formsum);
        System.out.println("tosum  "+tosum);
        System.out.println("total="+(formsum+tosum));
    }
}